<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useUserStore } from '@/stores/userStore'
import AlertNotification from '@/components/AlertNotification.vue'
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue'

const userStore = useUserStore()
const tableData = ref([])//存储用户列表数据
const loading = ref(false)// 用于表示数据是否正在加载
const dialogVisible = ref(false)// 控制对话框的状态
const formRef = ref(null)//表单实例的引用
const alertRef = ref(null)
const isEdit = ref(false)  // 是否为编辑模式
const editingUser = ref(null)//当前正在编辑的用户数据
const searchQuery = ref('')
// 表单数据
const form = ref({
  name: '',
  age: 18,
  address: '',
  phone: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }]
}


// computed计算属性搜索后的表格数据
const filteredTableData = computed(() => {
  if (!searchQuery.value) {
    return tableData.value
  }
  return tableData.value.filter(user => 
    user.name.toLowerCase().includes(searchQuery.value.toLowerCase())//搜索不区分大小写
  )
})

// 搜索框清空
const handleSearchClear = () => {
  searchQuery.value = ''
}

// 打开添加用户对话框
const handleAdd = () => {
  form.value = {
    name: '',
    age: 18,
    address: '',
    phone: ''
  }
  dialogVisible.value = true
}

// 获取用户数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await userStore.fetchUsers()
    tableData.value = res
  } catch (e) {
    console.error('获取数据失败:', e)
    alertRef.value?.showAlert('获取用户数据失败', 'error')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await userStore.updateUser(editingUser.value.id, form.value)
          alertRef.value?.showAlert('编辑信息成功')
        } else {
          await userStore.addUser(form.value)
          alertRef.value?.showAlert('添加用户成功')
        }
        dialogVisible.value = false
        await fetchData()  // 刷新列表
      } catch (error) {
        console.error(isEdit.value ? '编辑失败:' : '添加失败:', error)
        alertRef.value?.showAlert(
            isEdit.value ? '编辑信息失败' : '添加用户失败',
            'error'
        )
      }
    }
  })
}
// 处理编辑按钮
const handleEdit=(row)=>{
  // 设置编辑模式为 true
  isEdit.value = true
  // 保存正在编辑的用户数据
  editingUser.value = row
  //数据填充到表单中
  form.value = {
    name: row.name,
    age: row.age,
    address: row.address,
    phone: row.phone
  }
  dialogVisible.value = true
}
// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除用户 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await userStore.deleteUser(row.id)
      alertRef.value?.showAlert('删除用户成功')
      await fetchData()  // 刷新列表
    } catch (error) {
      // console.error('删除失败:', error)
      alertRef.value?.showAlert('删除用户失败', 'error')
    }
  })
}

// 处理搜索
const handleSearch = () => {
  if (searchQuery.value) {
    tableData.value = tableData.value.filter(item =>
      item.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  } else {
    fetchData()
  }
}

onMounted(() => {
  fetchData()
})
// watch监视，重置表单
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    form.value = {
      name: '',
      age: 18,
      address: '',
      phone: ''
    }
    isEdit.value = false
    editingUser.value = null
  }
})
</script>
<template>
  <div class="page-container">
    <alert-notification ref="alertRef"/>

    <el-card class="main-card">
      <!-- 搜索和添加区域 -->
      <div class="operation-area">
        <el-input
            v-model="searchQuery"
            placeholder="请输入用户名搜索"
            style="width: 200px"
            clearable
            @clear="handleSearchClear"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="handleSearch">
              <Search />
            </el-icon>
          </template>
        </el-input>

        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加用户
        </el-button>
      </div>

      <el-table :data="filteredTableData" border v-loading="loading">
        <el-table-column prop="name" label="用户名" align="center" />
        <el-table-column prop="age" label="年龄" width="100" align="center" />
        <el-table-column prop="address" label="地址" align="center" />
        <el-table-column prop="phone" label="电话" width="120" align="center" />
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; justify-content: center">
              <el-button type="primary" link @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑用户' : '添加用户'"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="1" :max="120" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
      </el-form>
      <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
</style>